#include <iostream>
#include <unistd.h>
#include <string>
#include <fcntl.h>

void setNonBlock(int fd)
{
    int f1=fcntl(fd,F_GETFL);
    if(f1<0)
    {
        perror("fcntl");
        return;
    }

    fcntl(fd,F_SETFL,f1 | O_NONBLOCK);
}
int main()
{
    char buffer[1024];
    std::string tip="Please Enter#";
    setNonBlock(0);
    while(true)
    {
        write(0,tip.c_str(),tip.size());
        //非阻塞，数据不就绪，就会以出错形式返回-1
        //read 读取失败返回值也是-1，
        //如何区分：通过errno判断，errno=EAGAIN表示数据不就绪，errno=EWOULDBLOCK表示数据不就绪
        int n=read(0,buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<"echo# "<<buffer<<std::endl;
        }
        else if(n==0)
        {
            std::cout<<"read file end!"<<std::endl;
            break;
        }
        else
        {
            if(errno!=EAGAIN && errno!=EWOULDBLOCK)
            {
                std::cout<<"read error"<<std::endl;
                sleep(1);
                continue;
            }
            else if(errno==EINTR)
            {
                std::cout<<"被中断，从新来"<<std::endl;
                sleep(1);
                continue;
            }
        }
        sleep(1);
    }
    return 0;
}